﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace LeastSquaresTechnique.Models
{
    /// <summary>
    /// 回归数据模型
    /// </summary>
    public class RegressionModel
    {
        #region 属性
        /// <summary>
        /// X序列
        /// </summary>
        public List<double> X { get; set; }

        /// <summary>
        /// Y序列
        /// </summary>
        public List<double> Y { get; set; }

        /// <summary>
        /// X的平均值LINQ写法
        /// </summary>
        public double AvgX =>X== null || X.Count() == 0 ? 0:X.Average();

        /// <summary>
        /// Y的平均值
        /// </summary>
        public double AvgY => Y == null || Y.Count() == 0 ? 0 : Y.Average();

        /// <summary>
        /// X序列
        /// </summary>
        private List<double> x=>X== null||X.Count()==0 ? new List<double>() : X.Select(m=>m-AvgX).ToList();
        
        /// <summary>
        ///Y序列 
        /// </summary>
        private List<double> y => Y == null || Y.Count() == 0 ? new List<double>() : Y.Select(m => m - AvgY).ToList();

        /// <summary>
        /// 计算系数a
        /// </summary>
        private double a { get; set; }

        /// <summary>
        /// 计算系数b
        /// </summary>
        private double b { get; set; }
        
        /// <summary>
        /// 计算参数ab
        /// </summary>
        #endregion
        public void Compute()
        {
            double answer1 = 0;
            double answer2 = 0;
            for(int i = 0; i < X.Count; i++)
            {
                answer1 += x[i] * y[i];
                answer2 += x[i] * x[i];
            }
            b=answer1/answer2;
            a = AvgY - b * AvgX;
        }

        /// <summary>
        /// 预测函数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public double Forecast(double x)
        {
            return a+b*x;
        }
    }
}
